package srdb.migration.dbhandler.enterprisedb;

import com.edb.NoticeListener;
import com.edb.PGConnection;
import com.edb.copy.CopyManager;
import com.edb.jdbc2.AbstractJdbc2Statement;

import java.io.InputStream;
import java.io.PrintStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Statement;
import org.apache.log4j.Logger;

import srdb.migration.Utility;
import srdb.migration.common.IMTKConnection;
import srdb.migration.i18n.ResourceHandler;

public class Data extends srdb.migration.dbhandler.srdb.Data {
	private static final String DBLINK_ORA_COPY_SQL = "SELECT dblink_ora_copy(?,?,?,?,?,?)";
	private static final int DBLINK_ORA_COPY_FEEDBACK_COUNT = 5000;

	public Data(IMTKConnection conn, int cpBatchSize) {
		super(conn, cpBatchSize);
		try {
			this.dblinkOraCopyStmt = this.dbConn
					.prepareStatement("SELECT dblink_ora_copy(?,?,?,?,?,?)");

			((AbstractJdbc2Statement) this.dblinkOraCopyStmt)
					.addNoticeListener(new NoticeListener() {
						public void noticeReceived(SQLWarning warn) {
							if (!warn.getMessage().equalsIgnoreCase("Row: 0")) {
								String[] arrMsg = warn.getMessage().split(":");
								Utility.getLogger()
										.info(ResourceHandler
												.getValue(
														"INFO_MIGRATED_ROWS",
														new String[] { arrMsg[1]
																.trim() }));
							}
						}
					});
		} catch (SQLException ex) {
			ex.printStackTrace();
		}
	}

	public void setTableData(String tableName, InputStream pis,
			char copyDelimiter) throws Exception {
		PGConnection copyConn = (PGConnection) this.conn.getConnection();
		CopyManager copy = copyConn.getCopyAPI();

		copy.copyIn(tableName, pis, copyDelimiter);
	}

	public int setTableDataViaDBLinkOra(String tableName, String targetSchema,
			String targetTable, boolean truncate) throws SQLException {
		int rowCount = 0;
		ResultSet resultSet = null;
		String tableQuery = "SELECT * FROM " + tableName;

		targetTable = targetTable.toLowerCase().equals(targetTable) ? targetTable
				.replaceAll("\"", "") : targetTable;
		try {
			this.dblinkOraCopyStmt.setString(1, "mtk_connection");
			this.dblinkOraCopyStmt.setString(2, tableQuery);
			this.dblinkOraCopyStmt.setString(3, targetSchema);
			this.dblinkOraCopyStmt.setString(4, targetTable);
			this.dblinkOraCopyStmt.setBoolean(5, truncate);
			this.dblinkOraCopyStmt.setInt(6, 5000);
			resultSet = this.dblinkOraCopyStmt.executeQuery();

			if (resultSet.next()) {
				try {
					rowCount = Integer.parseInt(resultSet.getString(1));
					Utility.getLogger().info(
							ResourceHandler.getValue("INFO_MIGRATED_ROWS",
									new String[] { String.valueOf(rowCount) }));
				} catch (NumberFormatException e) {
					Utility.getLogger().error(e.getMessage());
				}
			}

			this.dblinkOraCopyStmt.clearParameters();
			return rowCount;
		} finally {
			if (resultSet != null)
				resultSet.close();
		}
	}

	public boolean connectDBlinkOra(String srcDBURL, String userName,
			String password) throws SQLException {
		String[] url = Utility.parseOracleURL(srcDBURL);
		ResultSet resultSet = null;

		String conSql = "SELECT dblink_ora_connect(?,?,?,?,?,?,?)";
		PreparedStatement conStmt = null;
		try {
			conStmt = this.dbConn.prepareStatement(conSql);
			conStmt.setString(1, "mtk_connection");
			conStmt.setString(2, url[0]);
			conStmt.setString(3, url[2]);
			conStmt.setString(4, userName);
			conStmt.setString(5, password);
			conStmt.setInt(6, Integer.parseInt(url[1]));
			conStmt.setBoolean(7, false);
			resultSet = conStmt.executeQuery();
			int i = 0;
			String status;
			if (resultSet.next()) {
				status = resultSet.getString(1);
				if ((status == null) || (!status.equalsIgnoreCase("ok"))) {
					i = i + 1;
				}
				return true;
			}
			return false;
		} finally {
			if (resultSet != null) {
				resultSet.close();
			}

			if (conStmt != null)
				conStmt.close();
		}
	}

	public void disConnectDBlinkOra() throws SQLException {
		Connection con = this.conn.getConnection();
		Statement conStmt = null;
		try {
			if (this.dblinkOraCopyStmt != null) {
				this.dblinkOraCopyStmt.close();
			}

			conStmt = con.createStatement();
			conStmt.execute("SELECT dblink_ora_disconnect('mtk_connection')");
		} finally {
			if (conStmt != null)
				conStmt.close();
		}
	}
}

/*

 */